//
// Created by YueChuan on 2023/5/6.
//
#include "log.h"
#include "http_connection.h"
#include "iomanager.h"

static yuechuan::Logger::ptr g_logger = YUECHUAN_LOG_ROOT();

void test_pool() {
    yuechuan::http::HttpConnectionPool::ptr pool(
            new yuechuan::http::HttpConnectionPool("www.sylar.top", "", 80,
                                                   false, 10, 1000 * 30, 5));
    yuechuan::IOManager::GetThis()->addTimer(1000, [&pool]() {
        auto r = pool->doGet("/", 300);
        YUECHUAN_LOG_INFO(g_logger) << r->toString();
    }, true);
}

void run() {
    yuechuan::Address::ptr addr = yuechuan::Address::LookupAnyIPAddress("www.sylar.top:80");
    if (!addr) {
        YUECHUAN_LOG_INFO(g_logger) << "get addr error";
        return;
    }
    yuechuan::Socket::ptr sock = yuechuan::Socket::CreateTCP(addr);
    bool rt = sock->connect(addr);
    if (!rt) {
        YUECHUAN_LOG_ERROR(g_logger) << "connect " << addr->toString() << " failed";
        return;
    }

    yuechuan::http::HttpConnection::ptr conn(new yuechuan::http::HttpConnection(sock));
    yuechuan::http::HttpRequest::ptr req(new yuechuan::http::HttpRequest);
    req->setPath("/blog/");
    req->setHeader("host", "www.sylar.top");
    YUECHUAN_LOG_INFO(g_logger) << "req " << std::endl << *req;
    conn->sendRequest(req);
    auto rsp = conn->recvResponse();
    if (!rsp) {
        YUECHUAN_LOG_ERROR(g_logger) << "recv response error";
        return;
    }
    YUECHUAN_LOG_INFO(g_logger) << "rsp: " << std::endl << *rsp;
//    std::ofstream ofs("./rsp.dat");
//    ofs << *rsp;

    YUECHUAN_LOG_INFO(g_logger) << " +++++++++++++++++";
//

}

void test_static() {
    auto r = yuechuan::http::HttpConnection::DoGet("http://www.sylar.top/blog/", 3000);
    YUECHUAN_LOG_INFO(g_logger) << "result = " << r->result
                                << " error = " << r->error
                                << " rsp = " << (r->response ? r->response->toString() : "");
    test_pool();
}

int main(int argc, char **argv) {
    yuechuan::IOManager iom(2);
    iom.schedule(test_static);
//    test_pool();

    return 0;
}

